package com.web.servlet;


import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import com.web.JBDCUtils;

@WebServlet("/getStudentById")
public class GetStudentByIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String idStr = req.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                List<Student> students = JBDCUtils.query(Student.class, "SELECT * FROM students WHERE id = ?", id);
                if (!students.isEmpty()) {
                    out.println(students.get(0).toString());
                } else {
                    out.println("未找到该学生");
                }
            } catch (NumberFormatException e) {
                out.println("输入的 ID 不是有效的整数");
            }
        } else {
            out.println("请提供学生 ID");
        }
    }
}